<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天页面</title>
    <link type="text/css" href="../layui/css/layui.css">
</head>
<body>
<div id="chatbox">
    <div id="sendBox" style="float: left;">
        <input type="text" class="" id="editArea" placeholder="发送点什么吧"/>
        <div id="toUserId">5</div>
        <button class="layui-btn" id="send">发送</button>
        <button class="layui-btn" id="send2">发送到高晋峰</button>
        <button class="layui-btn" id="send1">发送到高晋峰二号</button>
        <br/>
        <p>已发送列表</p>
        <div id="sentList">
        </div>

        <div id="chat-box" style="width:600px">

            <div id="left" style="float: left;height: 400px;width: 150px;background: #ffffff;position:relative;border:solid 2px #4E5465;overflow: scroll">
                <div style="">
                    <input type="text" style="max-width: 90px"/> <span type="submit">搜索</>
                </div>
                <div id="user-item">
                    <img src="../upload/img/header/header.png" style="height: 20px;width: 20px">
                    <span>用户名Id</span>
                </div>
            </div>

            <div style="float: left;height: 400px;width: 400px;background: #4E5465;position:relative;border:solid 2px #4E5465">
                <div style="background: #ffffff;">
                    <span >与卖家 id 聊天</span>
                </div>
                <div id="content" style="height: 330px;width: 400px;padding-bottom: 10px;overflow: scroll;">
                    <p>内容</p>
                    <p>内容</p>
                    <p>内容</p>
                    <p>内容</p>


                </div>

                <div style="height: 50px;width: 400px;position: absolute;bottom: 0">
                    <textarea  style="height: 50px;width: 390px">编辑框</textarea>
                </div>
                <button style="position:absolute; bottom: 0;right: 0" id="add">发送</button>
            </div>
            <div id="msg-item" style="width: 300px;">
                <div style="float: right;">
                    <img src="../upload/img/header/header.png" style="width: 20px;height: 50px;">
                </div>
                <div id="msg-item-content" style="float:right;width: 250px; text-align:right; background: #2D93CA">     </div>
            </div>
        </div>


    </div>
    <div id="receiveBox" style="float: left; margin-left: 50px">
        <br/>
        <p>收信列表</p>
        <div id="receiveList">
        </div>

        <div id="msg-item1" style="width: 300px;">
            <div style="float: right;"><img src="../upload/img/header/header.png" style="width: 20px;height: 50px;">
            </div>
            <div id="msg-item-content1" style="float:right;max-width: 250px; text-align:left; background: #2D93CA">
                的喇嘛的喇嘛大咧咧
            </div>
        </div>

    </div>
    <button id="connect">连接</button>
    <button id="disconnect">断开连接</button>


</div>
</body>
<script src="../layui/layui.js"></script>
<script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/sockjs-client/1.0.2/sockjs.min.js"></script>
<script type="text/javascript">

    layui.use(['layer','jquery'], function () {
        var layer = layui.layer,
            $ = layui.$;


        var ws;
        var curTryNum = 0;
        var maxTryNum = 5;
        var stompClient = null;
        var socket =null;
        var stompHeader = {'clientId':localStorage.getItem("userId")};

        Date.prototype.Format = function (format) {
            var o = {
                "M+": this.getMonth() + 1,
                "d+": this.getDate(),
                "H+": this.getHours(),
                "m+": this.getMinutes(),
                "s+": this.getSeconds(),
                "S+": this.getMilliseconds()
            };
            if (/(y+)/.test(format)) {
                format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(format)) {
                    format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            return format;
        };



        $(document).ready(function () {


            $("#connect").click(function () {
                connect("/api/chat/");
            });
            $("#disconnect").click(function () {
                disconnect();
            });
            $("#send").click(function () {
                send();
            });
            $("#send1").click(function () {
                send1();
            });
            $("#send2").click(function () {
                send2();
            });
            layer.open({
                type:1
                ,content: $('#chat-box')
                ,area:'auto'
                ,scrollbar:false
                ,maxWidth:700
                ,maxHeight:500
                ,success:function () {
                    console.log(document.getElementById('add'));
                    $(document).on("click",'#add', function () {
                        var now = new Date();
                        var v = $('#content');
                        var c = "<div id=\"msg-item\" style=\"width: 300px;\"> <div style=\"float: right;\"> <img src=\"../upload/img/header/header.png\" style=\"width: 20px;height: 50px;\"> </div> <div id=\"msg-item-content\" style=\"float:right;width: 250px; text-align:right; background: #2D93CA\"> dsada </div> </div>";
                        v.append(c);
                        $('#sentList').append(c);

                        console.log(document.getElementById("content").scrollTop);
                        document.getElementById("content").scrollTop = document.getElementById("content").scrollHeight;
                    });
                }
            });


            function send() {
                var content = document.getElementById('editArea');
                document.getElementById('sentList').append(
                    "<p>" + content.value + "</p>"
                );
                if (content.value !== "") {
                    console.log("发送内容为：" + content.value);
                    stompClient.send("/ws/message", {}, JSON.stringify({'content': content.value}));
                    content.value = "";
                }
            }
            function send1() {
                var content = document.getElementById('editArea');
                document.getElementById('sentList').append(
                    "<p>" + content.value + "</p>"
                );
                if (content.value !== "") {
                    console.log("发送内容为：" + content.value);
                    stompClient.send("/ws/message", {}, JSON.stringify({'fromId':21,'toId':22,'content': content.value}));
                    content.value = "";
                }
            }
            function send2() {
                var content = document.getElementById('editArea');
                document.getElementById('sentList').append(
                    "<p>" + content.value + "</p>"
                );
                if (content.value !== "") {
                    console.log("发送内容为：" + content.value);
                    stompClient.send("/ws/message", {}, JSON.stringify({'fromId':22,'toId':21,'content': content.value}));
                    content.value = "";
                }
            }

            function connect(url) {
                if (socket==null){
                    socket = new SockJS(url);
                    stompClient = Stomp.over(socket);

                }
                curTryNum++;
                stompClient.connect(stompHeader, function (frame) {
                        setConnected(true);
                        console.log("连接成功："+new Date().Format("yyyy-MM-dd HH:mm:ss")+ + frame);
                        stompClient.subscribe('/topic/greeting', function (reply) {
                                console.log(reply);
                                document.getElementById('receiveList').append(
                                    "<p>" + reply.toString() + "</p>"
                                );
                            }
                        );
                        stompClient.subscribe('/user/'+localStorage.getItem("userId")+'/message',function (msg) {
                            console.log(msg);
                            document.getElementById('receiveList').append(
                                "<p>" + msg.toString() + "</p>"
                            );
                        });
                    }
                    ,function (frame) {
                        console.log(frame.toString());
                    }
                );

            }

            function disconnect() {
                if (stompClient != null) {
                    stompClient.disconnect();
                }
                setConnected(false);
                console.log("连接关闭 "+new Date().Format("yyyy-MM-dd HH:mm:ss"));
            }

            function setConnected(connected) {
                if (connected) {
                    console.log("显示对话");
                } else {
                    console.log("隐藏对话");
                }
            }


        });


    });


    /**
     * do WebSocket connect
     * @param url

     function connect(url) {
        curTryNum++;
        ws = null;
        if (window.WebSocket && window.WebSocket.prototype.send) {
            ws = new WebSocket(url);
        } else if ('MozWebSocket' in window) {
            ws = new WebSocket(url);
        } else {
            console.log("浏览器不支持websocket");
            window.close();
        }

        ws.onopen = function () {
            curTryNum = 0;
            console.log("连接成功开始检测心跳");
            heartCheck.start();

            document.getElementById("send").click(function () {
                var content = document.getElementById('editArea');
                document.getElementById('sentList').append(
                    "<p>" + content.value + "</p>"
                );
                if (content.value !== "") {
                    ws.send(content.value);
                    console.log("发送内容为：" + content.value);
                    content.value = "";
                }
            });


        };

        ws.onmessage = function (msg) {
            //心跳重启
            console.log("接收到信息=======>" + msg.data);
            console.log("心跳重启");
            heartCheck.restart();
            document.getElementById('receiveList').append(
                "<p>" + msg.data + "</p>"
            );
        };

        ws.onerror = function (ev) {
            console.log("连接出错==>" + ev.data);
        };

        ws.onclose = function (ev) {
            if (curTryNum < maxTryNum) {
                console.log("连接关闭10秒后将重新连接")
                setTimeout(function () {
                    connect(url);
                }, 10000);
            }else {
                console.log("连接次数超过十次,关闭连接");
            }
        };

        window.onbeforeunload = function () {
            ws.close();
        };
    }


    var pingServer = function () {

        String.prototype.getBytes = function () {

            var bytes = [];

            for (var i = 0; i < this.length; i++) {

                var charCode = this.charCodeAt(i);

                var cLen = Math.ceil(Math.log(charCode) / Math.log(256));

                for (var j = 0; j < cLen; j++) {

                    bytes.push((charCode << (j * 8)) & 0xFF);

                }

            }

            return bytes;

        };


        var payload = 'i';

        var buffer = new ArrayBuffer(payload.length);

        var intView = new Int8Array(buffer);

        for (var i = 0; i < intView.length; i++) {

            intView[i] = payload.getBytes()[i];

        }

        ws.send(intView);

        console.log("客户端已向服务器发送一个ping消息：【" + intView.toString() + "】");

    };

    var heartCheck = {
        timeout: 10000
        , timeoutObj: null
        , serverTimeoutObj: null
        , restart: function () {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            this.start();
        }
        , start: function () {
            var self = this;
            this.timeoutObj = setTimeout(function () {
                //若超过计时器时间则发送心跳包，若收到回复 onmessage:restart()
                pingServer();
                //若心跳未收到回复
                self.serverTimeoutObj = setTimeout(function () {
                    ws.close();
                }, self.timeout);
            }, this.timeout);
        }
    };
    */
</script>
</html>